import React ,{ PropTypes } from 'react'
import { Form, Row, message,  Col, Input, Button, Select, Modal, Message, DatePicker, Icon, Checkbox, InputNumber} from 'antd'
import { fetchPost } from './request'
import {origin_promotion} from '../../../utils/config'

const FormItem = Form.Item
const Option = Select.Option
const RangePicker = DatePicker.RangePicker
const CheckboxGroup = Checkbox.Group;

const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};

class Filter extends React.Component {
  constructor (props) {
    super(props)
    this.isModel = this.isModel.bind(this)
    this.addTemplate = this.addTemplate.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleModelReset = this.handleModelReset.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.addCoupontemplate = this.addCoupontemplate.bind(this)
    this.resetSearchParmas = this.resetSearchParmas.bind(this)
    this.disabledDate = this.disabledDate.bind(this)
    this.state = {
      data: [],
      batchNO: [],
      startTime: null,
      endTime: null,
      fileList: [],
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
      visible: false,
      batchgrant: false,
    }
  }
  handleSearch() {
    const { validateFields } = this.props.form
    this.props.changeIsLoading()
    validateFields((err, values) => {
      if(!err){
        let aa = {}
        if(values.couponNameS) {
          aa.couponName = values.couponNameS;
        }
        if(values.couponTypeS) {
          aa.couponType = values.couponTypeS;
        }
        if(values.appCode) {
          aa.appCode = values.appCode;
        }
        if(values.isValid) {
          aa.status = values.isValid;
        }
        aa.pageSize = 10;
        aa.currentPage = 1;
        this.props.getSearchData(aa)
      }
    })
  }
  handleModelReset() {
    const { resetFields } = this.props.form
    resetFields()
    this.setState({
      visible:false
    })
  }
  handleSubmit () {
    let self = this
    this.props.changeIsLoading()
    this.props.form.validateFields((err, values) => {
      if(!err) {
        let time = values.time
        let params = {}
        if(values.validtimeType !== '1') {
          values.startTime = time[0].format('YYYY-MM-DD HH:mm:ss'),
            values.endTime = time[1].format('YYYY-MM-DD HH:mm:ss')
          delete values.time
        }
        this.addCoupontemplate(values)
      }
    })
  }
  addCoupontemplate(params) {
    console.info(params.appCode);
    console.info(params.couponType);
    fetchPost(`/coupontemplate/add`, params, origin_promotion).then(json => {
      if (json.code === 0) {
        message.success('Lottery added successfully');
        this.handleReset()
      } else {
        message.error(json.msg);
      }
    });
  }
  resetSearchParmas () {
    this.props.changeIsLoading()
    this.props.form.resetFields()
    this.handleReset()
  }
  handleReset () {
    this.props.form.resetFields()
    this.setState({
      batchgrant: false,
      visible: false,
      fileList: [],
      startTime: null,
      endTime: null,
      params: {
        couponType: '1',
        validtimeType: '1',
        startTime: null,
        endTime: null,
      },
    }, () => {
      this.props.getData()
    })
  }

  disabledDate(current) {
    // Can not select days before today and today
    return current && current.valueOf() < Date.now();
  }
  addTemplate() {
    this.setState({
      visible: true,
    }, (rowData) => {
      this.isModel()
    })
  }
  isModel() {
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 12},
    }
    const rowData = this.state.rowData
    if(this.state.visible) {
      const { getFieldDecorator } = this.props.form
      return <Modal
        visible={this.state.visible}
        onCancel={() => {
          this.handleModelReset()
        }}
        title='New lottery ticket template'
        footer={null}
      >
        <div>
          <Form style={{width: '100%', margin: 'auto'}} horizontal >
            <FormItem
              {...formItemLayout}
              label="Lottery ticket name"
            >
              {getFieldDecorator('couponName', {
                rules: [
                  {
                    required: true,
                    message:'Please enter lottery ticket name'
                  }
                ]
              })(
                <Input placeholder="Please enter lottery ticket name"/>
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="Valid time type"
            >
              {getFieldDecorator('validtimeType', {
                initialValue: '1'.toString()
              })(
                <Select onChange={(e) => {
                  this.setState({
                    params: {
                      ...this.state.params,
                      validtimeType: e
                    }
                  })
                }} placeholder="Please select valid time type">
                  <Option key="1">Relatively</Option>
                  <Option key="2">Absolute</Option>
                </Select>
              )}
            </FormItem>
            {
              this.state.params.validtimeType === '1' ? <FormItem
                {...formItemLayout}
                label="Valid days"
              >
                {getFieldDecorator('validTime', {
                  rules: [
                    {
                      pattern: /^[0-9]*$/,
                      message: 'Please enter number'
                    },
                    {
                      required: true,
                      message:'Please enter valid days'
                    },
                  ]
                })(
                  <Input placeholder="Please enter valid days"/>
                )}
              </FormItem> : null
            }

            {
              this.state.params.validtimeType === '2' ? <FormItem
                {...formItemLayout}
                label="Duration"
              >
                {getFieldDecorator('time', {
                  rules: [
                    {
                      required: true,
                      message:'Please enter duration'
                    }
                  ]
                })(
                  <RangePicker
                    style={{width:'100%'}}
                    showTime

                    format="YYYY-MM-DD HH:mm:ss"
                  />
                )}
              </FormItem> : null
            }
            <FormItem
              {...formItemLayout}
              label="Lottery ticket type"
            >
              {getFieldDecorator('couponType', {
                initialValue: "1".toString(),
                rules: [
                  {
                    required: true,
                  }
                ]
              })(
                <Select onChange={(e) => {
                  console.log(e, 'e')
                  this.setState({
                    params: {
                      ...this.state.params,
                      couponType: e
                    }
                  })
                }} placeholder="Please enter lottery ticket type">
                  <Option key="1">Deduction</Option>
                  <Option key="2">Discount</Option>
                </Select>
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="Lottery ticket denomination"
            >
              {getFieldDecorator('couponAmount', {
                rules: [
                  {
                    pattern: /^([1-9]\d*|0)(\.\d{1,})?$/,
                    message: 'Please enter number'
                  },
                  {
                    required: true,
                    message:'Please enter the lottery ticket denomination'
                  }
                ]
              })(
                <div>
                  <Input placeholder="Please enter the lottery ticket denomination" style={{width: '80%'}} />
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {
                    this.state.params.couponType == 1 ?
                      <span style={{textAlign: 'right'}}>rupee</span> :
                      <span style={{textAlign: 'right'}}>fold</span>
                  }
                </div>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Description"
            >
              {getFieldDecorator('couponDesc', {
                rules: [
                  {
                    required: true,
                    message:'Please enter the description'
                  }
                ]
              })(
                <Input placeholder="Please enter the description"/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="Total"
            >
              {getFieldDecorator('totalNum', {
                initialValue: 0,
                rules: [
                  {
                    pattern: /^[0-9]*$/,
                    message: 'Please enter a positive integer'
                  },
                  {
                    required: true,
                    message:'Please enter the total'
                  }
                ]
              })(
                <InputNumber style={{width: '100%'}} min={0} defaultValue={0} ></InputNumber>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="App Channel"
            >
              {getFieldDecorator('appCode', {
                initialValue: window.sessionStorage.getItem('appCode')=='1'?'5':'2',
                disabled:true,
                rules: [
                  {
                    required: true,
                    message:'Please enter the app channel'
                  }
                ]
              })(
                <Select onChange={(e) => {
                  this.setState({
                    params: {
                      ...this.state.params,
                      appCode: e
                    }
                  })
                }}  placeholder="Please select the app channel type">
                      <Option  key="5" disabled>JYD</Option>
                      <Option  key="2" disabled>SDZZ</Option>
                </Select>
              )}
            </FormItem>
            <FormItem wrapperCol={{span: 12, offset: 5}}>
              <Button type="primary" onClick={this.handleSubmit}>OK</Button>
              <Button style={{marginLeft:16}}type="ghost" onClick={() => this.handleModelReset()}>Cancel</Button>
            </FormItem>
          </Form>
        </div>
      </Modal>
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Form
          className="ant-advanced-search-form"
          style={{marginBottom: 20}}>
          <Row gutter={40}>
            <Col span={6}>
              <FormItem {...formItemLayout} label={'Lottery ticket name'}>
                {getFieldDecorator('couponNameS')(
                  <Input  placeholder="Please enter lottery ticket name"/>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label={'Lottery ticket type'}>
                {getFieldDecorator('couponTypeS')(
                  <Select
                    placeholder="Please select lottery ticket type"
                  >
                    <Option value = {'1'}>Deduction</Option>
                    <Option value = {'2'}>Discount</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label={'Appcode'}>
                {getFieldDecorator('appCode')(
                  <Select
                    placeholder="Please choose Appcode"
                  >
                    <Option value = {'5'}>JYD </Option>
                    <Option value = {'2'}>SDZZ</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label={'is valid'}>
                {getFieldDecorator('isValid')(
                  <Select
                    placeholder="Please Choose"
                  >
                    <Option value = {'0'}>Offline</Option>
                    <Option value = {'1'}>Online</Option>
                    <Option value = {'2'}>Expired</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={24} style={{textAlign: 'right'}}>
              <Button type="primary" onClick={this.handleSearch}>Search</Button>
              <Button  style={{marginLeft :6}} onClick={this.resetSearchParmas}>Reset</Button>
              <Button type="primary" style={{marginLeft: 36}} ghost onClick={this.addTemplate}
              >New template</Button>

            </Col>
          </Row>
        </Form>
        {this.isModel()}
      </div>
    )
  }
}

Filter.propTypes = {
  form: PropTypes.object,
  handleSearch: PropTypes.func,
  addList: PropTypes.func,
}

export default Form.create()(Filter)
